#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OpenCloudOS 9 AI 包自动化验证脚本（第一阶段交付）
功能：
1. 根据 PyPI 包名自动 pip 安装
2. 执行独立测试用例
3. 生成 JSON 格式日志
"""

import json
import subprocess
import sys
from datetime import datetime

class AIPackageValidator:
    def __init__(self, test_cases_dir="test_cases"):
        self.results = []
        self.test_cases_dir = test_cases_dir

    def install_package(self, package_name: str) -> tuple[bool, str | None]:
        """安装单个 PyPI 包，返回 (是否成功, 错误信息)"""
        try:
            subprocess.run(
                [sys.executable, "-m", "pip", "install", package_name],
                check=True,
                capture_output=True,
                text=True,
                timeout=120
            )
            return True, None
        except subprocess.TimeoutExpired:
            return False, "安装超时 (>120s)"
        except subprocess.CalledProcessError as e:
            return False, e.stderr

    def run_test(self, package_name: str, test_script: str) -> dict:
        """运行测试脚本并返回结果字典"""
        try:
            result = subprocess.run(
                [sys.executable, "-c", test_script],
                capture_output=True,
                text=True,
                timeout=30
            )
            return {
                "package": package_name,
                "status": "PASS" if result.returncode == 0 else "FAIL",
                "stdout": result.stdout.strip(),
                "stderr": result.stderr.strip(),
                "timestamp": datetime.now().isoformat()
            }
        except subprocess.TimeoutExpired:
            return {
                "package": package_name,
                "status": "TIMEOUT",
                "stdout": "",
                "stderr": "测试执行超时 (>30s)",
                "timestamp": datetime.now().isoformat()
            }

    def validate_package(self, package_name: str, test_script: str) -> dict:
        """完整验证流程：安装 + 测试"""
        print(f"🔍 开始验证 {package_name} ...")
        install_ok, install_err = self.install_package(package_name)
        if not install_ok:
            result = {
                "package": package_name,
                "status": "INSTALL_FAIL",
                "stdout": "",
                "stderr": install_err,
                "timestamp": datetime.now().isoformat()
            }
            self.results.append(result)
            return result

        test_result = self.run_test(package_name, test_script)
        self.results.append(test_result)
        print(f"  ✅ {package_name} 验证完成，状态: {test_result['status']}")
        return test_result

    def save_results(self, output_file: str = "validation_results.json"):
        """将结果保存为 JSON 文件"""
        with open(output_file, "w", encoding="utf-8") as f:
            json.dump(self.results, f, indent=2, ensure_ascii=False)
        print(f"📊 结果已保存到 {output_file}")


# ----------------- 可直接运行的示例 -----------------
if __name__ == "__main__":
    validator = AIPackageValidator()

    # 示例 AI/数据科学包的极简测试用例
    test_cases = {
        "numpy": "import numpy, sys; print('numpy version:', numpy.__version__)",
        "pandas": "import pandas, sys; print('pandas version:', pandas.__version__)",
        "requests": "import requests; r = requests.get('https://pypi.org/simple/'); print('status:', r.status_code)"
    }

    for pkg, test in test_cases.items():
        validator.validate_package(pkg, test)

    validator.save_results()